<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*
* EXPORT COMMON class
*
* Provides methods common to the export scripts.
* @author Mark Grimshaw
* @version 1
* $Header: /cvsroot/wikindx/wikindx3/core/file/export/EXPORTCOMMON.php,v 1.27 2006/12/02 01:18:36 sirfragalot Exp $
*/
class EXPORTCOMMON
{
// Constructor
	function EXPORTCOMMON($db)
	{
		$this->db = $db;
		include_once("core/cite/CITE.php");
		$this->cite = new CITE($this->db, FALSE);
		include_once("core/html/HTML.php");
		include_once("core/file/FILE.php");
		$this->file = new FILE($this->db);
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/UTF8.php");
		$this->utf8 = new UTF8();
		$this->roman = array('/I/', '/II/', '/III/', '/IV/', '/V/', '/VI/', '/VII/', '/VIII/', '/IX/', '/X/');
	}
/*
* listFiles - list all exported files in the user's session directory within files/
* 
* @author Mark Grimshaw
*/
	function listFiles()
	{
		list($dirName, $deletePeriod, $fileArray, $paperArray) = $this->file->listFiles();
		if(!$dirName)
			$this->failure($this->errors->text("file", "read"));
		include_once("core/html/MISC.php");
		$filesDir = TRUE;
		if($dirName != 'files') // using FILES directory in config.php so possibly outside of web server htdocs/
			$filesDir = FALSE;
		$pString = MISC::p($this->messages->text("file", "contents"));
		$minutes = $deletePeriod/60;
		if(!empty($fileArray))
		{
			$pString .= $this->messages->text("file", "bibliographies") . MISC::br();
			foreach($fileArray AS $key => $value)
			{
				if($filesDir)
					$pString .= MISC::a("link", $key, $dirName . '/' . $key, "_blank") . MISC::br();
				else
				{
					$split = explode(".", $key);
					$title = $split[0];
					$extension = $split[1];
					$pString .= MISC::a("link", $key, "index.php?action=exportDownload" . 
						htmlentities("&hash=$title&filename=$key&extension=$extension"), "_new") . MISC::br();
				}
			}
			if(!empty($paperArray))
				$pString .= MISC::hr();
		}
		if(!empty($paperArray))
		{
			$pString .= $this->messages->text("file", "papers") . MISC::br();
			foreach($paperArray AS $fileName => $title)
				$pString .= MISC::a("link", $title . '.rtf', "index.php?action=wpExportDownload" . 
					htmlentities("&hash=$fileName&filename=$title"), "_new") . MISC::br();
		}
		$pString .= MISC::hr();
		$pString .= MISC::p($this->messages->text("file", "warning", " $minutes "));
		return $pString;
	}
/*
* writeFilenameToSession - add filename to session array
* 
* @author Mark Grimshaw
* @param string $fileName
*/
	function writeFilenameToSession($fileName)
	{
		if($sessVar = $this->session->getVar('fileExports'))
			$sessArray = unserialize($sessVar);
		else
			$sessArray = array();
		if(array_search($fileName, $sessArray) === FALSE)
		{
			$sessArray[] = $fileName;
			$this->session->setVar('fileExports', serialize($sessArray));
		}
	}
/*
* titleFormat - format and return the resource title from the supplied SQL $row
* 
* @author Mark Grimshaw
* @param assocArray $row
* @param boolean $bibtex
* @return string
*/
	function titleFormat($row, $bibtex = FALSE)
	{
// For book_chapter, 'title' is bibtex 'chapter' and 'collectionTitle' is bibtex 'title'
		if($bibtex && ($row['type'] == 'book_chapter'))
			return stripslashes($row['collectionTitle']);
		$noSort = $row['noSort'] ? stripslashes($row['noSort']) . ' ' : FALSE;
		if($row['subtitle'])
			$string = $noSort . stripslashes($row['title']) . ": " . stripslashes($row['subtitle']);
		else
			$string = $noSort . stripslashes($row['title']);
		if($bibtex)
			return $string;
// If !bibtex, remove any braces that have been inserted to maintain case of characters - only required for resource title
		return preg_replace("/[{|}]/", "", $string);
	}
/*
* grabNote - grab note from WKX_resource_note and strip BBCode and (optionally), multiple whitespace
* 
* @author Mark Grimshaw
* @param assocArray $row
* @param boolean $exportType
* @return string
*/
	function grabNote($row, $exportType)
	{
		$recordset = $this->db->select(array('WKX_resource_note'), array('text'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['resourceId']));
		$note = $this->db->fetchRow($recordset);
		if($note['text'])
		{
			if(($exportType == 'ris') || ($exportType == 'endnote'))
			{
				$text = $this->cite->parseCitations(stripslashes($note['text']), $exportType, FALSE);
				$text = HTML::stripBBCode($text);
			}
			else
				$text = stripslashes($note['text']);
// replace all whitespace (TABS, CR, \n etc.) with single space.
			if(($exportType == 'ris') || ($exportType == 'endnote'))
				return preg_replace("/\s/", " ", $text);
// For bibtex, ensure first letter is capitalized
			if($exportType == 'bibtex')
				return $this->utf8->utf8_ucfirst($text);
			return $text;
		}
		return '';
	}
/*
* grabAbstract - abstract from WKX_resource_abstract and strip BBCode and (optionally), multiple whitespace
* 
* @author Mark Grimshaw
* @param assocArray $row
* @param boolean $exportType
* @return string
*/
	function grabAbstract($row, $exportType)
	{
		$recordset = $this->db->select(array('WKX_resource_abstract'), array('abstract'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['resourceId']));
		$abstract = $this->db->fetchRow($recordset);
		if($abstract['abstract'])
		{
			if(($exportType == 'ris') || ($exportType == 'endnote'))
			{
				$text = $this->cite->parseCitations(stripslashes($abstract['abstract']), $exportType, FALSE);
				$text = HTML::stripBBCode($text);
			}
			else
				$text = stripslashes($abstract['abstract']);
// replace all whitespace (TABS, CR, \n etc.) with single space.
			if(($exportType == 'ris') || ($exportType == 'endnote'))
				return preg_replace("/\s/", " ", $text);
// For bibtex, ensure first letter is capitalized
			if($exportType == 'bibtex')
				return $this->utf8->utf8_ucfirst($text);
			return $text;
		}
		return '';
	}
/*
* pageFormat - return formatted pageStart and pageEnd with different delimiters
* 
* @author Mark Grimshaw
* @param assocArray $row
* @param string $exportType
* @return string
*/
	function pageFormat($row, $exportType)
	{
		$page = FALSE;
		if($row['pageStart'])
		{
			if($exportType == 'endnote')
				$page = stripslashes($row['pageStart']);
			else if($exportType == 'ris')
				$page = 'SP  - ' . stripslashes($row['pageStart']);
			else if($exportType == 'bibtex')
				$page = stripslashes($row['pageStart']);
		}
		if($row['pageEnd'])
		{
			if($exportType == 'endnote')
				$page .= '-' . stripslashes($row['pageEnd']);
			else if($exportType == 'ris')
				$page .= "\r" . 'EP  - ' . stripslashes($row['pageEnd']);
			else if($exportType == 'bibtex')
				$page .= '--' . stripslashes($row['pageEnd']);
		}
		if($page)
			return $page;
		return '';
	}
/*
* keywordFormat - return formatted keywords with different delimiters
* 
* @author Mark Grimshaw
* @param assocArray $row
* @param string $exportType
* @return string
*/
	function keywordFormat($row, $exportType)
	{
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		$recordset = $this->db->select(array('WKX_keyword'), array("keyword"), 
			" LEFT JOIN " . $this->db->formatTable("WKX_resource_keyword") . 
			" ON FIND_IN_SET(" . $this->db->formatField("WKX_keyword.id") . ", CONCAT(" . 
			$this->db->formatField('keywords') . ", ','))" . 
			" WHERE " . $this->db->formatField("WKX_resource_keyword.id") ." = " . 
			$this->db->tidyInput($row['resourceId']));
		if($this->db->numRows($recordset))
		{
			while($kw = $this->db->loopRecordSet($recordset))
				$k[] = stripslashes($kw['keyword']);
			if($exportType == 'endnote') // tabbed file
				return join(";", $k);
			else if($exportType == 'endnoteXml') // XML
			{
				$match = array('/"/', "/'/", "/&/", "/</", "/>/");
				$replace = array("&auot;", "&apos;", "&amp;", "&lt;", "&gt;");
				$string = '';
				foreach($k as $key => $value)
					$string .= "<keyword><style>" . preg_replace($match, $replace, $value) . 
					"</style></keyword>";
				return $string;
			}
			else if($exportType == 'ris')
			{
// asterisk (character 42) is not allowed in the author, keywords, or periodical name fields - replace with '#'
				foreach($k as $key => $value)
					$k[$key] = 'KW  - ' . preg_replace("/\*/", "#", $value);
				return join("\r", $k);
			}
			else if($exportType == 'bibtex')
				return join(",", $k);
		}
		return '';
	}
/*
* formatName - format one name depending on the export type
* 
* @author Mark Grimshaw
* @param assocArray $creatorRow
* @param string $exportType
* @return string
*/
	function formatName($creatorRow, $exportType)
	{
		$surname = $firstname = $initials = '';
// WIKINDX stores Jr., IV etc. at end of surname...
		if($creatorRow['surname'])
		{
			if($creatorRow['prefix'])
				$surname = stripslashes($creatorRow['prefix']) . " " . 
				stripslashes($creatorRow['surname']);
			else
				$surname = stripslashes($creatorRow['surname']);
		}
		if($creatorRow['firstname'])
			$firstname = stripslashes($creatorRow['firstname']);
		if($creatorRow['initials'])
		{
			if($exportType == 'endnote')
				$initials = implode(' ', explode(' ', stripslashes($creatorRow['initials'])));
			else if($exportType == 'ris')
				$initials = implode('.', explode(' ', stripslashes($creatorRow['initials']))) . ".";
			else if($exportType == 'bibtex')
				$initials = implode('. ', explode(' ', stripslashes($creatorRow['initials']))) . ".";
		}
		if($exportType == 'ris')
		{
			if($firstname && $initials)
				return $surname . ',' . $firstname . ',' . $initials;
			else if($firstname)
				return $surname . ',' . $firstname;
			else if($initials)
				return $surname . ',' . $initials;
		}
		else if($exportType == 'endnote')
		{
			if($firstname && $initials)
				return $surname . ',' . $firstname . ' ' . $initials;
			else if($firstname)
				return $surname . ',' . $firstname;
			else if($initials)
				return $surname . ',' . $initials;
		}
		else if($exportType == 'bibtex')
		{
			if(preg_match("/(.*)(Sr\.|jr\.)/i", $surname, $matches))
				$surname = trim($matches[1]) . ", " . trim($matches[2]);
			if(preg_match("/(.*)\s(I|II|III|IV|V|VI|VII|VIII|IX|X)$/", $surname, $matches))
				$surname = trim($matches[1]) . ", " . trim($matches[2]);
			if($firstname && $initials)
				
				return $surname . ", " . $firstname . ' ' . $initials;
			else if($firstname)
				return $surname . ", " . $firstname;
			else if($initials)
				return $surname . ", " . $initials;
		}
		return $surname; // if all else fails
	}
// Check if there any custom fields in the SQL set and provide options to map these to bibtex fields
	function getCustomFields($sql)
	{
// First, if there are no rows in WKX_resource_custom, return FALSE
		$recordset = $this->db->select(array("WKX_resource_custom"), array("id"));
		if(!$this->db->numRows($recordset))
			return FALSE;
// Now find out if any of these custom fields are being used in the current SQL set and grab the custom Label and id
		$sql = stripslashes($sql);
// Join in the custom tables and fields
		$selectReplace = ", " . $this->db->formatfield("custom_label") . ', ' . 
				$this->db->formatfield("customId") . ', ' . 
				$this->db->formatfield("custom_short") . ', ' . 
				$this->db->formatfield("custom_long") . ', ' . 
				$this->db->formatfield("custom_size") . ' FROM ';
		$joinReplace = " LEFT JOIN " . $this->db->formatTable("WKX_resource_custom") . 
				" ON " . $this->db->formatfield("WKX_resource.id") . "=" .
				$this->db->formatfield("WKX_resource_custom.resourceId") . 
				" LEFT JOIN " . $this->db->formatTable("WKX_custom") . 
				" ON " . $this->db->formatfield("WKX_custom.id") . "=" .
				$this->db->formatfield("WKX_resource_custom.customId");
		$whereReplace = "WHERE (" . $this->db->formatfield("WKX_resource_custom.custom_short") . 
			" IS NOT NULL OR " . $this->db->formatfield("WKX_resource_custom.custom_long") . 
			" IS NOT NULL) AND (";
		$replace = "$joinReplace $whereReplace";
		$sql = str_replace("FROM ", $selectReplace, $sql);
// Ensure "WHERE" has only one space before "(";
		$sql = preg_replace("/WHERE\s{1,}\(/", "WHERE (", $sql);
// quick search, power search and select have 'WHERE'.  Otherwise, replace just the join at the ORDER BY for list.
		if(strpos($sql, 'WHERE (') !== FALSE) // quick search, power search, select
			$sql = str_replace("WHERE (", $replace, $sql);
		else if(strpos($sql, 'WHERE') !== FALSE) // category tree
			$sql = str_replace("WHERE", substr($replace, 0, strlen($replace) - 1), $sql);
		else
			$sql = str_replace("ORDER BY", $joinReplace . " ORDER BY", $sql);
		$recordset = $this->db->query($sql);
		$customIDs = array();
		while($row = $this->db->loopRecordSet($recordset))
		{
			if($row['customId'])
				$customLabels[$row['customId']] = stripslashes($row['custom_label']);
		}
		if(empty($customLabels))
			return FALSE;
		$customLabels = array_unique($customLabels);
		$pString = MISC::p(MISC::b($this->messages->text("misc", "customFieldMap")));
		foreach($customLabels as $id => $label)
		{
			$text = $this->session->getVar("export_map_$id");
			$pString .= MISC::p(FORM::textInput($label, "map_$id", $text));
		}
		return $pString;
	}
// Error handling
	function failure($error)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->display);
	}
}
?>
